package net.ycxinxing.mcpebox.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Handler;
import dalvik.system.DexClassLoader;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import net.ycxinxing.mcpebox.mDialog;
import net.ycxinxing.mcpebox.ui.launcherGame;
import net.ycxinxing.mcpebox.utils.FileWrapper;
import android.content.pm.ApplicationInfo;
import net.ycxinxing.mcpebox.baseActivity;
import java.util.ArrayList;

public  class Utils
{
	static{
		System.loadLibrary("substrate");
	}
	public static void writeToFile(InputStream dataIns, File target) throws IOException
    {
		final int BUFFER = 1024;
		target.getParentFile().mkdirs();
		target.createNewFile();
		BufferedOutputStream bos = new BufferedOutputStream(
			new FileOutputStream(target));
		int count;
		byte data[] = new byte[BUFFER];
		while ((count = dataIns.read(data, 0, BUFFER)) != -1)
        {
			bos.write(data, 0, count);
		}
		bos.close(); 
	}
	public static String getSHA(File file)
	{
		if (!file.isFile())
		{
			return null;
		}
		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;

		try
		{
			digest = MessageDigest.getInstance("SHA1");
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 1024)) != -1)
			{
				digest.update(buffer, 0, len);
			}
			in.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}

		BigInteger bigInt = new BigInteger(1, digest.digest());
		return bigInt.toString(16);

	}
	public static void saveCurrentImage(Activity activity)
	{  //获取当前屏幕的大小 
		
	}
	
    public static File[] getSortFiles(File fileFolder)
    {
        File[] sortedFiles =fileFolder.listFiles();
        if (fileFolder.exists())
        {
            File[] files = fileFolder.listFiles();
            if (files != null && files.length > 0)
            {
                FileWrapper[] fileWrappers = new FileWrapper[files.length];
                for (int i = 0; i < files.length; i++)
                {
                    fileWrappers[i] = new FileWrapper(files[i]);
                }
                Arrays.sort(fileWrappers);//能够对实现了comparable接口的类的对象进行自动排序
                sortedFiles = new File[fileWrappers.length];
                for (int i = 0; i < sortedFiles.length; i++)
                {
                    sortedFiles[i] = fileWrappers[i].getFile();
                }
            }
        }
        return sortedFiles;
	}
	public static int dip2px(Context context, float dpValue)
	{
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
	public static int px2dip(Context context, float pxValue)
	{
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	public static void copyFile(File source, File dest)throws IOException
	{
		InputStream input = null;    
		OutputStream output = null;    
		try
		{
			input = new FileInputStream(source);
			output = new FileOutputStream(dest);        
			byte[] buf = new byte[1024];        
			int bytesRead;        
			while ((bytesRead = input.read(buf)) > 0)
			{
				output.write(buf, 0, bytesRead);
			}
		}
		finally
		{
			input.close();
			output.close();
		}
	}
	public static void LaunchGamePro(final String path, final String librarydir, final ApplicationInfo NativeAppInfo, final Activity ctx, final String PacketPath,final ArrayList<String> textruepacks)
	{
		ctx.startActivity(new Intent(ctx, launcherGame.class));
		final Thread launch=new Thread(){
			public void run()
			{
				try
				{
					Thread.sleep(500);
					//DexClassLoader cl=new DexClassLoader(path, ctx.getCacheDir().getAbsolutePath(), librarydir, ClassLoader.getSystemClassLoader().getParent());
					DexClassLoader cl=new DexClassLoader(path, ctx.getCacheDir().getAbsolutePath(), librarydir, ClassLoader.getSystemClassLoader().getParent());
					DexClassLoader pi=new DexClassLoader("/sdcard/ycxinxing/mcpebox/helper/helper.dex", ctx.getCacheDir().getAbsolutePath(), librarydir, cl);
					loadApkClassLoader(pi, ctx);
					Class<?> mcClass=pi.loadClass("net.ycxinxing.mcpebox.McHelper.MainActivity");
					Intent in=new Intent(ctx, mcClass);
					in.putExtra("libdir", librarydir);
					String YBtexturepack="";
					if (PacketPath == null)
					{
						in.putExtra("apkpath", path);
						YBtexturepack=path;
					}
					else
					{
						in.putExtra("apkpath", PacketPath);
						YBtexturepack=PacketPath;
					}
					AssetManager am = AssetManager.class.newInstance();
					baseActivity.log("原版资源"+am.getClass().getMethod("addAssetPath", String.class).invoke(am,YBtexturepack));
					if (NativeAppInfo == null)
					{
						in.putExtra("safemode", true);
					}
					else
					{
						in.putExtra("libpath", NativeAppInfo.nativeLibraryDir+"/"+System.mapLibraryName(NativeAppInfo.metaData.getString("net.ycxinxing.mcpebox.api.nativelibname")));
						in.putExtra("safemode", false);
						baseActivity.log("覆盖路径"+NativeAppInfo.publicSourceDir);
						baseActivity.log("资源覆盖"+am.getClass().getMethod("addAssetPath", String.class).invoke(am,NativeAppInfo.publicSourceDir));
						for(String textrue:textruepacks)
						{
							String texturepath="/sdcard/ycxinxing/mcpebox/texture/"+textrue;
							if(new File(texturepath).exists())
							{
								baseActivity.log("载入材质包"+texturepath+"结果"+am.getClass().getMethod("addAssetPath", String.class).invoke(am,texturepath));
							}
						}
						Field field = mcClass.getDeclaredField("am");

						field.setAccessible(true);
						field.set(mcClass,am);
					}
					
					ctx.startActivity(in);
					//replaceClassLoader(mApp.getMyClassLoader(),ctx);
					launcherGame.thiz.finish();
				}
				catch (final Exception e)
				{
					e.printStackTrace();
					launcherGame.thiz.runOnUiThread(new Runnable(){
							@Override
							public void run()
							{
								// TODO: Implement this method

								final mDialog dlg=new mDialog(launcherGame.thiz){
									@Override
									public void onButtonClick(int i)
									{
										launcherGame.thiz.finish();
										// TODO: Implement this method
									}
								};
								dlg.setCanClose(false);
								dlg.setMsg(e.toString() + "错误阻止了您启动mc");
								dlg.setButton3("确定");
								dlg.show();
							}
						});
				}
			}};
		new Handler().postDelayed(new Runnable()
			{

				@Override
				public void run()
				{
					// TODO: Implement this method


					try
					{
						//ZipContraFile(path,"/sdcard/ycxinxing/tmp/","");
						// TODO: Implement this method
						//String dome=((PathClassLoader)ctx.getClassLoader()).findLibrary("sdvm");
						String sha=getSHA(new File("/sdcard/ycxinxing/mcpebox/helper/helper.dex"));
						if (sha.equals("e5655b1d8c2d986bcedba3dae915742b59ad6b1c"))
						{
							launch.start();
						}
						else
						{
							final Activity tmp=launcherGame.thiz;
							final AlertDialog.Builder dlg=new AlertDialog.Builder(tmp);
							dlg.setTitle("您可能是盗版软件的受害者");
							dlg.setCancelable(false);
							dlg.setMessage("您可能使用了假的mchelper或者您使用的helper被恶意更改过。\n为了您的数据以及存档的安全，如果您无法确定helper的来源，请点击\"退出\"");
							dlg.setPositiveButton("退出", new DialogInterface.OnClickListener(){
									@Override
									public void onClick(DialogInterface p1, int p2)
									{
										launcherGame.thiz.finish();
										// TODO: Implement this method
									}
								});
							dlg.setNegativeButton("我知道风险，但我仍要继续", new DialogInterface.OnClickListener(){
									@Override
									public void onClick(DialogInterface p1, int p2)
									{
										launch.start();
										// TODO: Implement this method
									}
								});
							dlg.show();
						}
					}
					catch (final Exception e)
					{
						e.printStackTrace();
						final mDialog dlg=new mDialog(launcherGame.thiz){
							@Override
							public void onButtonClick(int i)
							{
								launcherGame.thiz.finish();
								// TODO: Implement this method
							}
						};
						dlg.setCanClose(false);
						dlg.setMsg(e.toString() + "错误阻止了您启动mc");
						dlg.setButton3("确定");
						dlg.show();
					}
				}
			}, 1000);
	}
	public static Field getDeclaredFieldRecursive(Class<?> clazz, String name)
	{
		if (clazz == null)
			return null;
		try
		{
			return clazz.getDeclaredField(name);
		}
		catch (NoSuchFieldException nsfe)
		{
			return getDeclaredFieldRecursive(clazz.getSuperclass(), name);
		}
	}
	@SuppressLint("NewApi")
	private static void loadApkClassLoader(DexClassLoader dLoader, Context ctx)
	{
		try
		{
			Class clazz_Ath = Class.forName("android.app.ActivityThread"); 
			Class clazz_LApk = Class.forName("android.app.LoadedApk");
			Object currentActivityThread = clazz_Ath.getMethod("currentActivityThread").invoke(null); 
			Field field1 = clazz_Ath.getDeclaredField("mPackages"); 
			field1.setAccessible(true); 
			Map mPackages = (Map) field1.get(currentActivityThread); 
			String packageName = ctx.getPackageName(); 
			WeakReference ref = (WeakReference) mPackages.get(packageName);
			Field field2 = clazz_LApk.getDeclaredField("mClassLoader");
			field2.setAccessible(true); 
			field2.set(ref.get(), dLoader); 
		}
		catch (Exception e)
		{
			e.printStackTrace(); 
		}
	}
	public static void deleteFile(File file)
	{

		if (file.exists())
		{ // 判断文件是否存在
			if (file.isFile())
			{ // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			}
			else if (file.isDirectory())
			{ // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++)
				{ // 遍历目录下所有的文件
					deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
				}
			}
			file.delete();
		}
		else
		{
			//
		}
	}
}
		
